from PyQt6.QtWidgets import QApplication, QMainWindow, QGraphicsView, QGraphicsScene, QGraphicsRectItem, QRubberBand
from PyQt6.QtGui import QPixmap
from PyQt6.QtCore import Qt, QPoint, QRect, QSize, QRectF


class ImageView(QGraphicsView):
    def __init__(self, image_path: str = '2.png'):
        super(ImageView, self).__init__()
        self.origin = QPoint()
        self.rubber_band = QRubberBand(QRubberBand.Shape.Rectangle, self.viewport())
        self.setScene(QGraphicsScene(self))
        self.set_image(image_path)  # 在初始化时设置图像

    def set_image(self, image_path, scale_factor=1.0):
        '''
        设置需要显示的图片，传入路径str
        :param image_path: 传入路径
        :param scale_factor: 缩放倍率
        :return: None
        '''
        pixmap = QPixmap(image_path)
        pixmap_item = self.scene().addPixmap(pixmap)  # 使用scene.addPixmap添加图像项
        # self.fitInView(pixmap_item, Qt.AspectRatioMode.KeepAspectRatio)
        pixmap_item.setTransformationMode(Qt.TransformationMode.SmoothTransformation)  # 使用平滑转换模式
        pixmap_item.setScale(scale_factor)  # 设置缩放比例
        self.setSceneRect(pixmap_item.boundingRect())  # 设置场景矩形以适配图像大小
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)

    def wheelEvent(self, event):
        mouse_point = event.position()
        delta = event.angleDelta().y() / 240
        factor = 1.1 if delta > 0 else 0.9
        self.scale(factor, factor)
        self.centerOn(mouse_point)


    # def mousePressEvent(self, event):
    #     if event.button() == Qt.MouseButton.LeftButton:
    #         self.origin = event.pos()
    #         #self.rubber_band.setGeometry(QRect(self.origin, QSize()))
    #         #self.rubber_band.show()
    #
    # def mouseMoveEvent(self, event):
    #     if self.rubber_band.isVisible():
    #         self.rubber_band.setGeometry(QRect(self.origin, event.pos()).normalized())
    #
    #
    # def mouseReleaseEvent(self, event):
    #     if event.button() == Qt.MouseButton.LeftButton:
    #         #self.rubber_band.hide()
    #         delta = event.pos() - self.origin
    #         self.translate(delta.x(), delta.y())
    #


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)

    window = QMainWindow()
    image_view = ImageView()
    window.setCentralWidget(image_view)
    window.show()

    sys.exit(app.exec())
